package com.huiminpay.merchant.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.domain.PageVO;
import com.huiminpay.common.cache.exception.BusinessCast;
import com.huiminpay.common.cache.exception.BusinessException;
import com.huiminpay.merchant.convert.StoreConvert;
import com.huiminpay.merchant.entity.Store;
import com.huiminpay.merchant.mapper.StoreMapper;
import com.yh.merchant.api.StoreServiceApi;
import com.yh.merchant.dto.StoreDTO;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @Author: HWW
 * @Date: 2021/8/2615:29
 * @Desc:
 */
@Service
public class StoreService implements StoreServiceApi {

    @Autowired
    private StoreMapper storeMapper;

    /**
     * 创建门店
     * @param storeDTO
     * @return
     * @throws BusinessException
     */
    @Override
    public StoreDTO createStore(StoreDTO storeDTO) throws BusinessException {
        //校验必要参数
        if(storeDTO == null){
            BusinessCast.cast(CommonErrorCode.E_110006);
        }
        Store store = StoreConvert.INSTANCE.dto2entity(storeDTO);
        storeMapper.insert(store);
        return StoreConvert.INSTANCE.entity2dto(store);
    }

    @Override
    public PageVO<StoreDTO> queryStoreByPage(StoreDTO storeDTO, Integer pageNo, Integer pageSize) {
        Page<Store> storePage = new Page<>(pageNo, pageSize);

        QueryWrapper<Store> storeQueryWrapper = new QueryWrapper<>();

        if (null == storeDTO && null == storeDTO.getMerchantId()) {
            BusinessCast.cast(CommonErrorCode.E_110006);
        }
        storeQueryWrapper.lambda().eq(Store::getMerchantId, storeDTO.getMerchantId());
        IPage<Store> storeIPage = storeMapper.selectPage(storePage, storeQueryWrapper);

        PageVO<StoreDTO> storeDTOS = new PageVO<>();
        storeDTOS.setCounts(storeIPage.getTotal());
        storeDTOS.setItems(StoreConvert.INSTANCE.entityList2dtoList(storeIPage.getRecords()));
        storeDTOS.setPage(pageNo);
        storeDTOS.setPageSize(pageSize);

        return storeDTOS;
    }
}
